/**
 * @author kobe
 * @date   16/06/01
 */

import Select from "../components/form/Select.js"

(function (lf, r) {
    var RC = r.createClass,
        ajax = lf.utils.ajax,
        getUrlParam = lf.utils.getUrlParam,
        doClose = lf.bridgeJs.doClose;


    const TYPE = getUrlParam('type'),
        RESIDENT = 'resident',
        PROPRIETOR = 'proprietor';

    var Resident = RC({

        render: function () {
            var a = 0;
            var list = this.props.info.map(function (e) {
                a++;
                return (
                    <InputContainer key={a} info={e} ref="inputCtr"/>
                )
            });
            return (
                <div className="resident">
                    {list}
                </div>
            )
        }
    });

    var Proprietor = RC({
        render: function () {
            var a = 0;
            var list = this.props.info.map(function (e) {
                a++;
                return (
                    <InputContainer key={a} info={e} ref="inputCtr"/>
                )
            });
            return (
                <div className="proprietor">
                    {list}
                </div>
            )
        }
    });

    var ChooseInput = RC({
        render: function () {
            var info = this.props.info;
            return (
                <div>
                    <div className="title">{info.title}</div>
                    <div className="mui-input-row">
                        <Select addClass="select-input" ref='select' value={info.val} name={info.name}
                                groupCode={info.code}/>
                    </div>
                </div>
            )
        }
    });

    var TextInput = RC({
        componentDidMount: function () {

        },
        blurFn: function () {
            var me = this;
            var info = me.props.info;

            if (info.name == "idCard") {

                //身份证号验证
                var idNum = $('#idCard').val() || me.props.setMsg[3].info.val,
                    reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;

                if (reg.test(idNum)) {
                    ajax({
                        type: 'GET',
                        data: {
                            idNum: idNum
                        },
                        success: function (data) {
                            //成功
                            if (data.code == '200') {
                                if (data.data == null) {
                                    $('#phone').val('').removeAttr('readOnly');
                                } else {
                                    $('#phone').val(data.data.loginAccount).attr('readOnly', 'readonly');
                                    $('#name').val(data.data.realName).attr('readOnly', 'readonly');
                                }
                            }
                            else {
                                alert(data.desc);
                            }
                        }.bind(this)
                    }, lf.finger.api.household.getCustByIdNum);

                }
                else {
                    alert('身份证号错误');
                }
                ;


            }
        },
        render: function () {
            var info = this.props.info;
            if (info.readonly == 'readonly' && !(info.val == '')) {
                var readonly = true
            }
            return (
                <div>
                    <div className="title">{info.title}</div>
                    <div className="mui-input-row">
                        <input className="text-input" id={info.name} readOnly={readonly} onBlur={this.blurFn}
                               type="text" ref="test" placeholder={info.val}/>
                    </div>
                </div>
            )
        }
    });


    var InputContainer = RC({
        render: function () {
            var info = this.props.info;
            var setInput = info.type == 'text' ? info.type == 'choose' ? "" :
                <TextInput info={info.info} ref="inputText"/> : <ChooseInput info={info.info} ref="choose"/>;
            return (
                <div>
                    {setInput}
                </div>
            )
        }
    });

    var FromGroup = RC({
        componentDidMount: function () {
            var me = this;
            var $sent = $(r.findDOMNode(this.refs.sent));

            // 也得优化这一块
            if (this.props.info.status == 'register') { //住户登记
                lf.utils.slideDownKeyboard();
                $sent.on('tap', function () {
                    //registerResident

                    var checkPhone = false, checkId = false;

                    //手机号验证
                    var telNum = $('#phone').val(),
                        reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;
                    if (reg.test(telNum) || telNum == "") {
                        checkPhone = true;
                    }
                    else {
                        mui.toast('手机号错误');
                    }
                    ;

                    //身份证号验证
                    var idNum = $('#idCard').val() || me.props.setMsg[3].info.val,
                        reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;

                    if (reg.test(idNum)) {
                        checkId = true;
                    }
                    else {
                        mui.toast('身份证号错误');
                    }
                    ;

                    var info = me.props.info;
                    var data = {
                        proprietorId: info.proprietorId,
                        houseId: info.houseId,
                        picUrl: "str",
                        name: $('#name').val(),
                        mobile: telNum,
                        idNum: $('#idCard').val(),
                        sex: $('#sex').val(),
                        workUnit: $('#unit').val(),
                        residentRelation: $('#relationship').val(),
                        nativePlace: $('#place').val(),
                        projectId: info.projectId,
                    };

                    if (checkPhone && checkId) {
                        $sent.attr("disabled", "disabled");
                        ajax({
                            type: 'POST',
                            data: data,
                            success: function (data) {
                                //成功
                                if (data.code == '200') {
                                    mui.toast('更新成功');
                                    setTimeout(function () {
                                        doClose();
                                    }, 1000);
                                }
                                else {
                                    alert(data.desc);
                                    $sent.removeAttr("disabled");
                                }
                            }
                        }, lf.finger.api.household.registerResident);
                    }
                    else {
                        $sent.removeAttr("disabled");
                    }


                });
            } else {

                if (TYPE == PROPRIETOR) { //业主信息更新
                    lf.utils.slideDownKeyboard();
                    $sent.on('tap', function () {

                        var check = false;


                        //手机号验证
                        var telNum = $('#emergencyPhone').val() || me.props.setMsg[3].info.val,
                            regPhone = /^0?1[3|4|5|7|8][0-9]\d{8}$/,
                            regHome = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;


                        if (regPhone.test(telNum) || telNum == '' || regHome.test(telNum)) {
                            check = true;
                        }
                        else {
                            $('#emergencyPhone').val('');
                            mui.toast('紧急联系电话错误');
                        }
                        ;

                        var data = {
                            proprietorId: me.props.info.proprietorId,
                            picUrl: 'str',
                            sex: $('#sex').val(),
                            workUnit: $('#workUnti').val() || me.props.setMsg[1].info.val,
                            emergencyContact: $('#emergencyContact').val() || me.props.setMsg[2].info.val,
                            emergencyPhone: telNum
                        };

                        if (check) {
                            $sent.attr("disabled", "disabled");
                            ajax({
                                type: 'POST',
                                data: data,
                                success: function (data) {
                                    //成功
                                    if (data.code == '200') {
                                        mui.toast('更新成功');
                                        setTimeout(function () {
                                            doClose();
                                        }, 1000);

                                    }
                                    else {
                                        alert(data.desc);
                                        $sent.removeAttr("disabled");
                                    }
                                }
                            }, lf.finger.api.household.registerProprietor);
                        } else {
                            $sent.removeAttr("disabled");
                        }

                    })
                }
                else { //住户信息更新


                    $sent.on('tap', function () {
                        lf.utils.slideDownKeyboard();
                        $sent.attr("disabled", "disabled");
                        var info = me.props.setMsg;
                        var checkPhone = false;

                        //手机号验证
                        var telNum = $('#phone').val() || info[3].info.val,
                            reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;

                        if (reg.test(telNum) || telNum == "") {
                            checkPhone = true;
                        }
                        else {
                            mui.toast('手机号错误');
                        }
                        ;

                        var data = {
                            residentId: me.props.info.residentId,
                            custGlobalId: me.props.info.custGlobalId,
                            houseId: me.props.info.houseId,
                            picUrl: 'str',
                            name: $('#name').val() || info[0].info.val,
                            sex: $('#sex').val(),
                            idNum: $('#idCard').val() || info[2].info.val,
                            mobile: telNum,
                            residentRelation: $('#relationship').val(),
                            workUnit: $('#unit').val() || info[5].info.val,
                            nativePlace: $('#place').val() || info[6].info.val,
                        };

                        if (checkPhone) {
                            ajax({
                                type: 'POST',
                                data: data,
                                success: function (data) {
                                    //成功
                                    if (data.code == '200') {
                                        mui.toast('更新成功');
                                        setTimeout(function () {
                                            doClose();
                                        }, 1000);
                                    }
                                    else {
                                        alert(data.desc);
                                        $sent.attr("disabled", true);
                                    }
                                }
                            }, lf.finger.api.household.updateResident);
                        }
                        else {
                            $sent.removeAttr("disabled");
                        }

                    })


                }
            }

        },
        render: function () {

            var setContainer = TYPE == PROPRIETOR ? <Resident info={this.props.setMsg} ref="type"/> :
                <Proprietor info={this.props.setMsg} ref="type"/>;
            return (
                <from className="mui-input-group" ref="form">
                    {setContainer}
                    <button type="submit" className="mui-btn mui-btn-primary mui-btn-block save-btn" ref="sent">保存
                    </button>
                </from>
            )
        }
    });


    var Register = RC({
        getInitialState: function () {
            return ({type: '', proprietorId: ''})
        },
        render: function () {

            var outputMsg = [
                {
                    type: 'text',
                    info: {
                        val: '(必填)',
                        name: 'name',
                        ref: 'name',
                        title: "您的姓名",

                    },

                },
                {
                    type: 'choose',
                    info: {
                        title: "请选择性别",
                        code: 'SEX',
                        val: '0',
                        name: 'sex',
                        ref: 'sex',

                    },

                },
                {
                    type: 'text',
                    info: {
                        title: "您的身份证号",
                        val: '(必填)',
                        name: 'idCard',
                        ref: 'idCard',

                    },

                },
                {
                    type: 'text',
                    info: {
                        title: "您的联系电话",
                        val: '(选填)',
                        name: 'phone',
                        ref: 'phone',

                    },

                },
                {
                    type: 'choose',
                    info: {
                        title: "与业主的关系",
                        val: '09',
                        code: 'RESIDENT_RELATION',
                        name: 'relationship',
                        ref: 'relationship',

                    },

                },
                {
                    type: 'text',
                    info: {
                        title: "您的工作单位",
                        val: '(选填)',
                        name: 'unit',
                        ref: 'unit',

                    },

                },
                {
                    type: 'text',
                    info: {
                        title: "您的户口所在地",
                        val: '(选填)',
                        name: 'place',
                        ref: 'place',

                    },

                },
            ]

            return (
                <div className="property-register">
                    <FromGroup info={this.props.info} setMsg={outputMsg}/>
                </div>
            )

        }
    });

    var Update = RC({
        getInitialState: function () {
            return ({
                info: {
                    customer: '',
                    residentHouse: '',
                }
            })
        },
        componentWillMount: function () {
            if (TYPE == PROPRIETOR) {
                ajax({
                    type: 'POST',
                    data: {
                        proprietorId: this.props.info.proprietorId
                    },
                    success: function (data) {
                        //成功
                        if (data.code == '200') {
                            this.setState({info: data.data});
                        }
                        else {
                            alert('找不到业主信息');
                        }
                    }.bind(this)
                }, lf.finger.api.household.getProprietorOfRegister);
            }
            else if (TYPE == RESIDENT) {
                ajax({
                    type: 'POST',
                    data: {
                        houseId: getUrlParam('houseId'),
                        residentId: getUrlParam('residentId'),
                    },
                    success: function (data) {
                        //成功
                        if (data.code == '200') {
                            this.setState({info: data.data})
                        }
                        else {
                            alert(data.desc);
                        }
                    }.bind(this)
                }, lf.finger.api.household.getResident);
            }
            else {
                console.log(false);
            }

        },
        render: function () {

            //设置表单参数

            if (TYPE == PROPRIETOR) { //业主

                var outputMsg = [
                    {
                        type: 'choose',
                        info: {
                            val: this.state.info.sex,
                            code: 'SEX',
                            name: 'sex',
                            title: '性别',
                        }
                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.workUnit || '(选填)',
                            name: 'workUnti',
                            title: '工作单位',
                        }

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.emergencyContact || '(选填)',
                            name: 'emergencyContact',
                            title: '紧急联系人'
                        }

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.emergencyPhone || '(必填)',
                            name: 'emergencyPhone',
                            title: '紧急联系电话'
                        }
                    }
                ];
            }
            else if (TYPE == RESIDENT) { //住户设置表单参数

                var outputMsg = [
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.name,
                            name: 'name',
                            ref: 'name',
                            title: '姓名',
                            readonly: 'readonly'

                        },

                    },
                    {
                        type: 'choose',
                        info: {
                            val: this.state.info.customer.sex,
                            code: 'SEX',
                            name: 'sex',
                            ref: 'sex',
                            title: '性别'
                        },

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.customer.idNum || '',
                            name: 'idCard',
                            ref: 'idCard',
                            title: '身份证号',
                            readonly: 'readonly'
                        },

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.loginAccount || this.state.info.mobile,
                            name: 'phone',
                            ref: 'phone',
                            title: '联系电话',
                            readonly: 'readonly'
                        },

                    },
                    {
                        type: 'choose',
                        info: {
                            val: this.state.info.residentHouse.residentRelation,
                            name: 'relationship',
                            code: 'RESIDENT_RELATION',
                            ref: 'relationship',
                            title: '与业主的关系',
                            readonly: 'readonly'
                        },

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.workUnit || '',
                            name: 'unit',
                            ref: 'unit',
                            title: '工作单位'
                        },

                    },
                    {
                        type: 'text',
                        info: {
                            val: this.state.info.customer.nativePlace,
                            name: 'place',
                            ref: 'place',
                            title: '户口所在地'
                        },

                    },
                ];
            }
            else {
                outputMsg = ''
            }

            return (
                <div className="property-update">
                    <FromGroup info={this.props.info} setMsg={outputMsg}/>
                </div>
            )
        }
    });

    var Container = RC({
        getInitialState: function () {
            return ({
                info: '',
            })
        },
        componentWillMount: function () {

            var me = this;

            var urlMsg = { //获取信息
                projectId: getUrlParam('projectId') || '',
                houseNum: getUrlParam('houseNum') || '',
                type: getUrlParam('type') || '',
                proprietorId: getUrlParam('proprietorId') || '',
                houseId: getUrlParam('houseId') || '',
                residentId: getUrlParam('residentId') || '',
                status: getUrlParam('status') || '',
                custGlobalId: getUrlParam('globalId') || ''
            }

            if (TYPE == PROPRIETOR) { //获取业主ID
                ajax({
                    data: {
                        projectId: getUrlParam('projectId'),
                        houseNum: getUrlParam('houseNum')
                    },
                    success: function (data) {
                        //成功
                        if (data.code == '200') {
                            if (data.data) {
                                urlMsg.proprietorId = data.data.proprietorId;
                            }
                            me.setState({info: urlMsg});
                        }
                        else {
                            alert(data.desc);
                        }
                    }
                }, lf.finger.api.household.getProprietor);
            }

            else if (TYPE == RESIDENT) { //获取住户ID
                me.setState({info: urlMsg});
            }

        },
        render: function () {

            var inputType = this.state.info.status;

            if (inputType == 'update') {
                inputType = <Update info={this.state.info}/>
            } else if (inputType == 'register') {
                inputType = <Register info={this.state.info}/>
            } else {
                inputType = ''
            }


            //增加mask防止用户误按
            return (
                <div className="property-register">
                    <div className="mask"></div>
                    {inputType}
                </div>
            )
        }
    });

    lf.bridgeJs.getUser(function (user) {
        r.render(
            <Container user={user}/>,
            document.getElementById('root'), function () {
                $('#root').css('background', 'none');
                $('.mask').hide(1000);
            }
        )
    })

})(liefeng, React);
